import os

from Base import SockerBase


class Server:
    """ 初始化 启动"""
    def __init__(self, port=50000):
        self.sock = SockerBase(port)
        self.sock.init_server()

    def start(self):
        while True:
            self.sock.print('Before request')
            self.sock.start_listen()
            self.sock.print('Accept request')
            self.send()
            self.sock.print('finish request')

    def send(self):
        self.request = self.sock.myrece()
        if self._send_check():
            self.sock.mysend({'able': True})
            self._do_send()
        else:
            self.sock.mysend({'able': False})

    def _send_check(self):
        self.path = self.request.get('path', 'None')
        return self._check_file()

    def _check_file(self):
        if not os.path.exists(self.path):
            self.sock.print('File does not exit')
            return False
        else:
            return True

    def _do_send(self):
        with open(self.path, 'rb') as f:
            self.sock.mysend(f.read())

if __name__ == '__main__':
    s = Server()
    s.start()